/*
 * jsextension.cpp
 *
 *  Created on: 15-Oct-2009
 *      Author: pmui
 *      
 *      
 *      Flickr key: 3fc6661fb929a329653d967d98bab683
 *      Flickr secret: d238f2b245386845
 */
#include <QDir>
#include <QUrl>
#include <QDebug>
#include <QFile>
#include <QDirIterator>
#include "Photo.h"
#include "Twitpic.h"

Photo::Photo()
{
	// TODO Auto-generated constructor stub
	m_upload = new TwitPic();
	
	connect(m_upload, SIGNAL(uploadReady()), SLOT(doUploadReady()));
	
	m_photoDirs << "c:\\data\\images\\" <<  "e:\\Images\\Camera\\" << "e:\\Images\\kamera\\" << "C:\\data\\Images\\kamera\\";
	m_fsWatcher = new QFileSystemWatcher(this);
	
	for(int i=0;i<m_photoDirs.count();i++)
		m_fsWatcher->addPath(m_photoDirs[i]);
	
	connect( m_fsWatcher, SIGNAL(directoryChanged(const QString &)), 
				this, SLOT(doReload()));
}

QStringList Photo::getAvailablePhotos()
{
	QStringList photos;
	
	photos << "Dummy";
	
	for(int i=0;i<m_photoDirs.count();i++)
		getDirectory(photos, m_photoDirs[i]);
	
	return photos;
}

void Photo::getDirectory(QStringList &photos, const QString &dir)
{
	QStringList filter;
	filter << "*.jpg";
		
	QDirIterator it(dir, QDirIterator::Subdirectories);
	
	while (it.hasNext()) {
		QFileInfo file(it.next());
		
		if(file.completeSuffix() == "jpg")
		{
			QUrl url = QUrl::fromLocalFile(file.absoluteFilePath());
			photos << url.toString();
		}
	}
}

QByteArray Photo::getImageData(const QString &photo)
{
	QFile file(photo);
	file.open(QIODevice::ReadOnly);
	QByteArray byteArray = file.readAll();
	file.close();
	return byteArray;
}

void Photo::uploadPhoto(const QString &photo)
{
	m_upload->upload(QUrl(photo).toLocalFile());
}

void Photo::doUploadReady()
{
	emit uploadReady();
}

void Photo::doReload()
{
	emit reload();
}
